package com.example.demo.serviceImpl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.demo.dao.slaver.WdfPayLogerMapper;
import com.example.demo.pojo.WdfPayLoger;
import com.example.demo.service.ImsMembersPaylogService;
import com.example.demo.service.ImsMembersService;
import com.example.demo.service.WXPayService;
import com.example.demo.wx.pay.HttpUtil;
import com.example.demo.wx.pay.PayConfigUtil;
import com.example.demo.wx.pay.PayToolUtil;
import com.example.demo.wx.pay.XMLUtil4jdom;
import com.github.wxpay.sdk.WXPayUtil;

@Service
public  class WXPayServiceImpl implements WXPayService {
	String appid = PayConfigUtil.APP_ID; // appid
	String mch_id = PayConfigUtil.MCH_ID; // 商业号
	String key = PayConfigUtil.API_KEY; // key
	
	@Autowired
	public WdfPayLogerMapper wdfPayLogerMapper;
	@Autowired
	public ImsMembersPaylogService imsMembersPaylogService;
	
	
	@Override
	public synchronized Map<String,String> weixinPay(String userName, String totalFee) throws Exception {
		//订单号
		String out_trade_no =getTradeNum();
		// 随机字符串
		String nonce_str = WXPayUtil.generateNonceStr();
		// 获取发起电脑 ip
		String spbill_create_ip = PayConfigUtil.CREATE_IP;
		// 回调接口
		String notify_url = PayConfigUtil.NOTIFY_URL;
		String trade_type = "NATIVE";

		String urlCode=null;
		try {
			SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
			packageParams.put("appid", appid);
			packageParams.put("mch_id", mch_id);
			packageParams.put("nonce_str", nonce_str);
			packageParams.put("body", "话费充值"); // （商品名称）
			packageParams.put("out_trade_no", out_trade_no);
			packageParams.put("total_fee", totalFee); // 价格的单位为分
			packageParams.put("spbill_create_ip", spbill_create_ip);
			packageParams.put("notify_url", notify_url);
			packageParams.put("trade_type", trade_type);

			String sign = PayToolUtil.createSign("UTF-8", packageParams, key);
			packageParams.put("sign", sign);
			String requestXML = PayToolUtil.getRequestXml(packageParams);
			String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);
			@SuppressWarnings("rawtypes")
			Map map = XMLUtil4jdom.doXMLParse(resXml);
			urlCode = (String) map.get("code_url");
			//添加日志
			WdfPayLoger loger = new WdfPayLoger();
			loger.setCreateTime(new Date());
			loger.setOrderNumber(out_trade_no);
			loger.setUserName(userName);
			loger.setWxMoney(new Integer(totalFee));
			loger.setState((byte)1);
			 int insert = wdfPayLogerMapper.insert(loger);
			if(insert==0) {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		Map<String, String> map = new HashMap<String,String>();
		map.put("outTradeNo", out_trade_no);
		map.put("url", urlCode);
		return map;
	}


	
	public String getTradeNum() {
		 SimpleDateFormat format = new SimpleDateFormat("YYYYMMddHHmmss");
		 String format2 = format.format(new Date());
		 int hashCodeV = UUID.randomUUID().toString().hashCode();  
		 if(hashCodeV < 0) {
			//有可能是负数
			 hashCodeV = - hashCodeV;  
		 }
		 return "wdf"+format2+String.format("%012d", hashCodeV);  
	}
	
	
	/**
	 * 查寻状态
	 * 
	 * @return
	 */
	public Map<Object, String> queryPaySatue(String out_trade_no) {
		Map<Object, String> result = new HashMap<Object, String>();
		Map<String, String> map = null;
		while (true) {
			if (map == null) {
				result.put("500", "支付失败");
			}
			if (map.get("trade_state").equals("SUCCESS")) {
				result.put("200", "支付成功");
			}
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				result.put("500", "支付失败");
				return result;
			}
		}
	}

	/**
	 * 关闭订单
	 * 
	 * @param out_trade_no
	 * @return
	 */
	@Override
	public synchronized Object closeOrder(String out_trade_no) {
		String nonce_str = WXPayUtil.generateNonceStr();
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		packageParams.put("appid", appid);
		packageParams.put("mch_id", mch_id);
		packageParams.put("nonce_str", nonce_str);
		packageParams.put("out_trade_no", out_trade_no);

		String sign = PayToolUtil.createSign("UTF-8", packageParams, key);
		packageParams.put("sign", sign);
		String requestXML = PayToolUtil.getRequestXml(packageParams);
		String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);
		try {
			@SuppressWarnings({ "rawtypes", "unused" })
			Map map = XMLUtil4jdom.doXMLParse(resXml);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;

	}

	/**
	 * 查寻支付状态
	 * 
	 * @param out_trade_no
	 * @return
	 */
	@SuppressWarnings("unused")
	public static Object getWxPayState(String out_trade_no) {
		SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
		packageParams.put("appid", PayConfigUtil.APP_ID);
		packageParams.put("mch_id", PayConfigUtil.MCH_ID);
		packageParams.put("nonce_str", WXPayUtil.generateNonceStr());
		packageParams.put("out_trade_no", out_trade_no);
		String sign = PayToolUtil.createSign("UTF-8", packageParams, PayConfigUtil.API_KEY);
		packageParams.put("sign", sign);
		String requestXML = PayToolUtil.getRequestXml(packageParams);
		String resXml = HttpUtil.postData(PayConfigUtil.PAY_URL, requestXML);
		Map<String, String> map = null;
		try {
			map = WXPayUtil.xmlToMap(resXml);
			String tradeState = map.get("trade_state");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resXml;

	}
}
